package com.project.server;

import com.project.service.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 处理socket线程类
 */
public class SocketThread implements Runnable{
    //MIME类型
    private static String header = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html;charSet=utf-8\r\n" +
            "\r\n";
    private Socket socket;
    public SocketThread(Socket socket){
        this.socket = socket;

        new Thread(this).start();
    }

    @Override
    public void run() {
        try {


            //从socket中，得到读取流，用于从客户端接收数据
            InputStream in = socket.getInputStream();
            //从socket中，得到写入流，用于将数据发送给客户端
            OutputStream out = socket.getOutputStream();
            //将读取流封装成请求对象，以便更好的读取数据
            Request request = new Request(in);
            //将写入流封装成响应对象，以便更好的发送数据
            Response response = new Response(out);
            System.out.println("request:"+request);

            //得到客户端请求的URL路径
            String url = request.getUrl();
            //根据url路径，得到对应的业务组件对象
//            Servlet servlet = ServletFactory.getService(url);
            Servlet servlet = AnnotationServletFactory.getServlet(url);

            //向客户端发送数据
            out.write(header.getBytes());
           if(servlet != null){//业务组件
               servlet.service(request,response);
           }
            else {//请求的是文件
                response.sendFile(url);
            }

            //关闭流
            out.close();
            in.close();
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
